package com.dream.controller;

import com.alibaba.fastjson.JSON;
import com.dream.utils.ResultCommon;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;

/**
 * 专门负责文件上传
 * Servlet 3.0 新特性文件上传
 */
@WebServlet("/FIleUploadController.do")
@MultipartConfig
public class FIleUploadController extends BaseServlet {

    /**
     * 文件上传
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ResultCommon resultCommon=null;
        try {
            Collection<Part> parts = request.getParts();
            for (Part part : parts) {
                // 创建要保存的File对象
                String header = part.getHeader("content-disposition");
                System.out.println(header); // form-data; name="file"; filename="12324.jpg"
                String fileName = this.getNameByHeader(header);
                System.out.println("上传的原始文件名字:" + fileName); // 12324.jpg
                String kuozhanming = fileName.substring(fileName.lastIndexOf("."));
                System.out.println("扩展名:"+kuozhanming);
                String newFileName=UUID.randomUUID().toString()+kuozhanming;
                System.out.println("上传服务器生成的文件名:"+newFileName);
                //获取服务器上传的真实路径
                String realPath = request.getServletContext().getRealPath("/upload" + "/" + newFileName);
                System.out.println("服务器上传的地址:"+realPath);
                // 保存文件
                part.write(realPath);
                System.out.println("文件上传成功!");
                resultCommon=new ResultCommon(200,"文件上传成功",newFileName);
            }
        } catch (IOException e) {
            e.printStackTrace();
            resultCommon=new ResultCommon(500,"文件上传失败",null);
        }
        String jsonString = JSON.toJSONString(resultCommon);
        response.getWriter().write(jsonString);
    }


    // 从消息头中获取上传的文件名称
    private String getNameByHeader(String msg) {
        System.out.println(msg);
        String[] arr1 = msg.split(";");
        String fn = "";
        if (arr1.length == 3) {
            fn = arr1[2].split("=")[1].replaceAll("\"", "");
        }
        return fn;
    }

}
